
(function() {
	var app = angular.module('autoDiscoveryApp', [ 'ui.bootstrap' ]);
	app
			.controller(
					'autoDiscoveryController',
					function($http,$scope, $log, $uibModal) {
						var basePath = $scope.getAppBasePath();
						$scope.insertComponent = {};
						$scope.deleteComponent = {};
						var controller = this;
						controller.parameter = {};
						controller.queryParameter = "";
						this.warningConfigList = [];
						this.indexList = [];
//						$scope.assertMangeUrl = "http://10.4.31.20:3309";
						var username=localStorage.getItem('obj');
						var userObj=JSON.parse(username)
						
						$scope.listid=[];
						this.queryCondition = {
							"regionIndex" : "",
							"roomnameIndex" : "",
							"racknameIndex" : "",
							"ipAddrIndex":"",
							"page" : 1,
							"pageSize" : 5,
						};
						this.paginationInfo = {
							"maxSize" : 5,
							"totalPages" : 0,
							"totalElements" : 0
						};
						$scope.clickEvent = function() {
							controller.queryCondition.page = controller.queryCondition.forwordPage;
							loadData();
						}

						// 跳转页数，回车事件
						$scope.enterEvent = function(e) {
							var keycode = window.event ? e.keyCode : e.which;
							if (keycode == 13) {
								$scope.clickEvent();
							}
						}

						this.pageChanged = function() {
							loadData();
						}
						
						// 完成全选全部选事件
						$("#check_all").click(
								function() {
									$(".check_item").prop("checked",
											$(this).prop("checked"));
								});
						// 选中单个元素，如果单个元素选择满了，那么第一个主元素也被选中
						$(document)
								.on(
										"click",
										".check_item",
										function() {
											if ($(".check_item:checked").length == $(".check_item").length) {
												$("#check_all").prop("checked",
														true);
											}
											if ($(".check_item:checked").length == 0) {
												$("#check_all").prop("checked",
														false);
											}
										});
						
						
						
						// 程序初期化
						this.init = function() {
							loadData();
							
						}
						this.init();

						// 加载数据
						function loadData() {
							if ($(".check_item:checked").length == 0) {
								$("#check_all").prop("checked", false);
							}
						}
							// 获取树状图数据
							var zTreeObj;
					        // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
					       var setting = {
								check: {
									enable: true
							//        chkboxType : { "Y" : "", "N" : "" }
								},
								data: {
									simpleData: {
										enable: true
									}
								}
							};
						
					        // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
					       //树的的获取
					       var zNodes=[];
					       $.ajax({
								 type : "get",
								 url :basePath+"/getIps",
								 dataType : "json",
								 success:function(data){
									 zNodes=angular.fromJson(data)
//									 console.log(zNodes);
									 zTreeObj = $.fn.zTree.init($("#warningSelectIP"), setting, zNodes)
							         function zTreeOnExpand(event,treeId, treeNode) {
							                var nodes = zTreeObj.getSelectedNodes();
							                if (nodes.length > 0&& treeNode.level != 0&& treeNode.level != 1) {
											"refresh"
							                }
							           }
							          function zTreeOnClick(event,treeId, treeNode) {
							          }	 
								
								 }	 
						     })
						     	var selectedIp=[];
					            $("#yearInput").click(function(){
					            	$("#warningSelectIP").show();
									//获取选中的ip
						            
						            
//									$("#warningSelectIP").toggle();
								})
								 $('#defaultRule').on('click',function(e) {
									 var target = $(e.target);
									 if(!target.is('#yearInput') && !target.is('#warningSelectIP *')){
										 var treeObj=$.fn.zTree.getZTreeObj("warningSelectIP");
								            selectedIp=treeObj.getCheckedNodes(true);
								            var name='';
//								            console.log(selectedIp);
								            if(selectedIp.length !="0" && selectedIp.length !=undefined){
								            	
								            	for (var i = 0; i < selectedIp.length; i++) {
									            	if (selectedIp[i].chidren == undefined && selectedIp[i].isParent == false) {
//									            		console.log(selectedIp[i]);
									            		name+=selectedIp[i].name+';';
														  $("#yearInput").val(name.slice(0,-1));//去除最后的逗号
													}
									            }
								            }else{
								            	 $("#yearInput").val("");
								            }
										 if ( $('#warningSelectIP').is(':visible') ) {
										      $('#warningSelectIP').hide();   
										    }									
									 }
									
								 })

					       $scope.ruletype=[
		                        {id : "0", name : "预警"},
				        	    {id : "1", name : "危险"},
				        	    {id : "2", name : "严重"},
				        	  
				        	    ];
					       
//							规则配置加载数据
							 $.ajax({
							 type : "get",
							 url :basePath + "/queryIndexRule",
							 dataType : "json",
							 success : function(res) {	
								 $scope.ruletable=angular.fromJson(res);
							 //手动刷新
							 	$scope.$apply();  
								 },errro:function(){
									 console.log("请求错误！")
								 }
							 });

						
					
						//保存指标规则配置setrule
						$(".setrule").click(function(){
							
							//gotoStep(2);
							  $(".ruletable tr").eq(0).find("#rulewarintype option:selected").val();
							var conditons = []; 
//							console.log($(".ruletable tr").eq(0).find("#ruledesc").val());
//							console.log($(".ruletable tbody tr"))
							for(var i=1;i<= $(".ruletable tbody tr").length;i++){
								var contectsObj = new Object(); 
								contectsObj.desc=$(".ruletable tr").eq(i).find("#ruledesc").val();
								contectsObj.name=$(".ruletable tr").eq(i).find("#rulename").html();
								contectsObj.min=$(".ruletable tr").eq(i).find("#lv1_low").val();
								contectsObj.max=$(".ruletable tr").eq(i).find("#lv1_high").val();
								contectsObj.updateUser =userObj.name;
								contectsObj.level =$(".ruletable tr").eq(i).find("#rulewarintype option:selected").val();
								contectsObj.rulewhite=$(".ruletable tr").eq(i).find("#rulewhite option:selected").val();
								conditons.push(contectsObj);
							}
//							console.log(selectedIp);
							if(selectedIp.length==0){
								  alert("请选择主机号！")
							}else{
								  gotoStep(2);
							}
							//判断是否有数据更改
//							 var result = [];
//							for(var i = 0; i < conditons.length; i++){
//				                var obj = conditons[i];
//				                var desc1 = obj.desc;
//				                var min1 = obj.min;
//				                var max1 = obj.max;
//				                var level1 = obj.level;
//				                var isExist = false;
//				                for(var j = 0; j < $scope.ruletable.length; j++){
//				                    var aj = $scope.ruletable[j];
//				                    var desc2 = aj.desc;
//				                    var min2 = aj.min;
//				                    var max2 = aj.max;
//				                    var level2 = aj.level;
//				                    if(desc1 == desc2 && min1==min2 && max1 == max2 && level1==level2){
//				                        isExist = true;
//				                        break;
//				                    }
//				                }
//				                if(!isExist){
//				                    result.push(obj);
//				                }
//				            }
//							 if(result.length!=0 && selectedIp.length==0){
//					                alert("请选择主机号！")
//					         }else{
//					        	  gotoStep(2);
//					         }
//					         console.log(result);
							
							
						})
						
						//预警联系人保存
						$(".warinPeople").click(function(){
							var warinpeoplename= $("#warinpeoplename").val();
							var warincontant= $('input:radio[name="warincontant"]:checked').val();
							var warinphone= $("#warinphone").val();
							var warinemail= $("#warinemail").val();
						
							if(warinpeoplename=="" && warincontant==null && warinphone=="" && warinemail==""){
								gotoStep(3);
							}else{
								if(warinpeoplename !="" && warincontant==null){
									alert("填写完整的信息！");
								}else{
									
									if(warinphone=="" && warinemail==""){
										alert("请填写手机号或邮箱！");
									}else{
										gotoStep(3);
										
									}
									
								}
							}
						})
						//危险联系人
						$(".dangerPeople").click(function(){
							var dangerpeople= $("#dangerpeople").val();
							var dangercontant= $('input:radio[name="dangercontant"]:checked').val();
							var dangerphone= $("#dangerphone").val();
							var dangeremail= $("#dangeremail").val();
							if(dangerpeople=="" && dangercontant==null && dangerphone=="" && dangeremail==""){
								gotoStep(4);
							}else{
								if(dangerpeople !="" && dangercontant==null){
									alert("填写完整的信息！");
								}else{
									
									if(dangerphone=="" && dangeremail==""){
										alert("请填写手机号或邮箱！");
									}else{
										gotoStep(4);
										
									}
									
								}
							}
						})
						//严重联系人判断
						$(".jump4").click(function(){
							var warin=$("#warinpeoplename").val();
							var danger=$("#dangerpeople").val();
							var serious=$("#seriouspeople").val();
							
							var seriouspeople= $("#seriouspeople").val();
							var seriouscontant= $('input:radio[name="seriouscontant"]:checked').val();
							var seriousphone= $("#seriousphone").val();
							var seriousemail= $("#seriousemail").val();
							if(warin =="" && danger == "" && serious ==""){
								alert("请填写联系人！")
							}else{
								if(seriouspeople=="" && seriouscontant==null && seriousphone=="" && seriousemail==""){
									gotoStep(5);
								}else{
									if(seriouspeople !="" && seriouscontant==null){
										alert("填写完整的信息！");
									}else{
										
										if(seriousphone=="" && seriousemail==""){
											alert("请填写手机号或邮箱！");
										}else{
											gotoStep(5);
											
										}
										
									}
								}
								
								
							}
							
						})
						//频率数据加载
						 $.ajax({
							 type : "get",
							 url :basePath +"/queryFrequency",
							 dataType : "json",
							 success : function(res) {	
								 $scope.frequercyTable=angular.fromJson(res);
								
							 //手动刷新
							 	$scope.$apply();  
							 },errro:function(){
								 console.log("请求错误！")
							 }
							 });
//						//频率展示判断
						var freselectedIp=[];
						 $(".frequency").click(function(){
							 var treeObj=$.fn.zTree.getZTreeObj("hostztree");
							  freselectedIp=treeObj.getCheckedNodes(true);
					            console.log(freselectedIp);
					           
					            if($scope.selectedSite2 != undefined && $scope.selectedSite3 !=undefined && freselectedIp.length==0){
					            	 console.log($scope.selectedSite1);
					            	 console.log($scope.selectedSite2);
					            	alert("请选择主机号！");
								}else{
									gotoStep(6);
								}
					           
						 })
						 
						 //频率展示树
						 getTreeData();
						// 获取树状图数据
							function getTreeData() {
								var address = "";
								$.ajax({
									type : "POST",
									url : basePath + "/data/selectMonitoringIndex",
									dataType : "json",
									contentType : "application/json",
									success : function(data) {
										//修改数据添加父级节点“监控指标配置”
										var resultArrary = {
												"id"       : "0",
												"name"     : "监控指标配置",
												"isParent" : "true",
												"children" :JSON.parse(data),
										}
										var setting = {
											// 异步加载POST方法   异步加载需要解决进页面后直接全选 点击修改  但是此时树结构是不完整的问题；
											//思路:js做判断当全选时不走之前的修改方法，后添加一个修改所有的接口，接着会发现全选二级目录也会遇到类似问题
/*											//本人懒且树结构的数据量小我选择放弃异步加载，直接load整棵树，后期用异步加载请注意上述问题。（异步加载的后台方法保留可用）
* 												async : {
												enable : true,
												dataType : "text",
												type : "post",
												url : basePath + "/data/asyncGetKPITreeData",
												autoParam : [ "id" ],
												dataFilter : ajaxDataFilter
											},*/
											// checkBox 效果
											check : {
												enable : true,
												chkStyle : "checkbox"
											},
											callback : {
												onClick : zTreeOnClick,  //点击节点事件
												//onExpand: zTreeOnExpand  //点击节点前+号加载
											}
										};

										// 返回数据转成json
										function ajaxDataFilter(treeId, parentNode, responseData) {
											responseData = JSON.parse(responseData);
											return responseData;
										}
										;
										var zTreeObj = $.fn.zTree.init($("#hostztree"), setting,
												resultArrary);
										//点击展开第一级
										$("#hostztree_1_switch").click();
										
										//点击节点方法加载kpi的详细配置信息
										function zTreeOnClick(event, treeId, treeNode) {
											if(treeNode.isParent == false){//判断为末级子节点
												//将当前点击选中的节点配置信息添加到下拉框展示
												//告警次数阈值赋值
												$("#selectedSiteFiveInitValue").val(treeNode.times);
												//超阈值告警频率赋值
												$("#selectedSiteSixInitValue").val(treeNode.minutes);
											}
										}	//点击节点方法 结束
										
									}
								});
					}//getTreeData结束
					
						//运维命令
						 getTreeData2();
						// 获取树状图数据
							function getTreeData2() {
								var address = "";
								$.ajax({
									type : "POST",
									url : basePath + "/data/selectMonitoringIndex",
									dataType : "json",
									contentType : "application/json",
									success : function(data) {
										//修改数据添加父级节点“监控指标配置”
										var resultArrary = {
												"id"       : "0",
												"name"     : "监控指标配置",
												"isParent" : "true",
												"children" :JSON.parse(data),
										}
										var setting = {
											// 异步加载POST方法   异步加载需要解决进页面后直接全选 点击修改  但是此时树结构是不完整的问题；
											//思路:js做判断当全选时不走之前的修改方法，后添加一个修改所有的接口，接着会发现全选二级目录也会遇到类似问题
/*											//本人懒且树结构的数据量小我选择放弃异步加载，直接load整棵树，后期用异步加载请注意上述问题。（异步加载的后台方法保留可用）
* 												async : {
												enable : true,
												dataType : "text",
												type : "post",
												url : basePath + "/data/asyncGetKPITreeData",
												autoParam : [ "id" ],
												dataFilter : ajaxDataFilter
											},*/
											// checkBox 效果
											check : {
												enable : true,
												chkStyle : "checkbox"
											},
											callback : {
												onClick : zTreeOnClick,  //点击节点事件
												//onExpand: zTreeOnExpand  //点击节点前+号加载
												onCheck: zTreeOnCheck
											}
										};

										// 返回数据转成json
										function ajaxDataFilter(treeId, parentNode, responseData) {
											responseData = JSON.parse(responseData);
											return responseData;
										}
										;
										var zTreeObj = $.fn.zTree.init($("#hostztree2"), setting,
												resultArrary);
										var nodes = zTreeObj.getSelectedNodes();
									
										for (var i=0, l=nodes.length; i < l; i++) {
											zTreeObj.checkNode(nodes[i], true, true);
										}
										//点击展开第一级
										$("#hostztree2_1_switch").click();
										
										//点击节点方法加载kpi的详细配置信息
										var queryKpidata=[];
										var modifykip=[];
										function zTreeOnCheck(event, treeId, treeNode) {
											$.ajax({
												 type : "get",
												 url :basePath + "/queryKpi",
												 dataType : "json",
												 success : function(res) {	
													 queryKpidata=angular.fromJson(res);
//												
													if(treeNode.checked == true){
														modifykip.push(treeNode.name);
														console.log(modifykip);
															for(var i=0;i<queryKpidata.length;i++){
//																if(modifykip[j]==queryKpidata[i].kpi_name){
//																	console.log(queryKpidata[i].kpi_name)
//																	$(".modifytable tr td").eq(i).text(queryKpidata[i].kpi_name);
//																}
//																console.log(treeNode);
																if(treeNode.name==queryKpidata[i].kpi_name &&  queryKpidata[i].kpi_name !="" &&  queryKpidata[i].kpi_name != undefined){	
																	$(".modifytable tr").eq(i+1).find("#kpi_desc").html(queryKpidata[i].kpi_desc);
																	$(".modifytable tr").eq(i+1).find("#kpi_name").html(treeNode.name);
																	$(".modifytable tr").eq(i+1).find("#cmdtd").html('<input type="text" class="form-control" id="kpi_cmd" value="'+queryKpidata[i].kpi_cmd+'" style="height:21px;width: 89%;padding:0;margin:0;font-size: 1px">');
																}
																
															}
														
													}else{	
														for(var i=0;i<queryKpidata.length;i++){
															if(treeNode.name == queryKpidata[i].kpi_name &&  queryKpidata[i].kpi_name !="" &&  queryKpidata[i].kpi_name != undefined){
//																alert("确定取消"+$(".modifytable tr").eq(i+1).find("#kpi_desc").html()+"?");
																$(".modifytable tr").eq(i+1).find("#kpi_desc").html("");
																$(".modifytable tr").eq(i+1).find("#kpi_name").html("");
																$(".modifytable tr").eq(i+1).find("#cmdtd").html("");
															}
														}
														modifykip.splice($.inArray(treeNode.name,modifykip),1);
													}
//													console.log(modifykip);
												 },errro:function(){
													 console.log("请求错误！")
												 }
											});		
											
										};
										
										function zTreeOnClick(event, treeId, treeNode) {
										
											if(treeNode.isParent == false){//判断为末级子节点
												//将当前点击选中的节点配置信息添加到下拉框展示
												//告警次数阈值赋值
												$("#selectedSiteFiveInitValue").val(treeNode.times);
												//超阈值告警频率赋值
												$("#selectedSiteSixInitValue").val(treeNode.minutes);
											}
										}	//点击节点方法 结束
										
									}
								});
					}//getTreeData结束
					//运维命令
							$.ajax({
								 type : "get",
								 url :basePath +"/queryKpi",
								 dataType : "json",
								 success : function(res) {	
									 $scope.operation=angular.fromJson(res);
								
								 //手动刷新
								 	$scope.$apply();  
								 },errro:function(){
									 console.log("请求错误！")
								 }
							});		
					
					//一次性提交
					$(".endsumbit").click(function(){
						var selectedSite2;
						var selectedSite3;
						if($scope.selectedSite2 == undefined && $scope.selectedSite3 == undefined){
							$scope.selectedSite2="";
							$scope.selectedSite3="";
						}
						
						//运维命令table
							var modifies = []; 
							for(var i=1;i<= $(".modifytable tbody tr").length;i++){
								var contectsObj = new Object(); 
								contectsObj.kpi_desc=$(".modifytable tr").eq(i).find("#kpi_desc").html();
								contectsObj.kpi_name=$(".modifytable tr").eq(i).find("#kpi_name").html();
								contectsObj.kpi_cmd=$(".modifytable tr").eq(i).find("#kpi_cmd").val();
								if(contectsObj.kpi_desc !="" && contectsObj.kpi_name !=""){
									modifies.push(contectsObj);
								}
//								modifies.push(contectsObj);
							}
							
						//配置规则
						var conditons = []; 
						for(var i=1;i<= $(".ruletable tbody tr").length;i++){
							var contectsObj = new Object(); 
							contectsObj.desc=$(".ruletable tr").eq(i).find("#ruledesc").val();
							contectsObj.name=$(".ruletable tr").eq(i).find("#rulename").html();
							contectsObj.level =$(".ruletable tr").eq(i).find("#rulewarintype option:selected").val();
							contectsObj.min=$(".ruletable tr").eq(i).find("#lv1_low").val();
							contectsObj.max=$(".ruletable tr").eq(i).find("#lv1_high").val();
							contectsObj.rulewhite=$(".ruletable tr").eq(i).find("#rulewhite option:selected").val();
							conditons.push(contectsObj);
						}
						//配置规则kpi
					var ruleInput;
					ruleInput=$("#yearInput").val().split(";");
					console.log(ruleInput.length)
					var rul=[];
					var rulekpi=[];
					for(var i=0;i<ruleInput.length;i++){
						rul[i]={
			        			"name":ruleInput[i],
			        	}
						if(rul[i].name !=""){
							rulekpi.push(rul[i]);
						}
					}
					console.log(rulekpi)
					//频率展示kpi选择
					 	var freselectedIp=[];
						 var treeObj=$.fn.zTree.getZTreeObj("hostztree");
						  freselectedIp=treeObj.getCheckedNodes(true);
							var req=[]
							var freqkpi=[];
							for (var i = 0; i < freselectedIp.length; i++) {
						        if (freselectedIp[i].chidren == undefined && freselectedIp[i].isParent == false) {
						        	req[i]={
						        			"name":freselectedIp[i].name,
						        	}
						        	freqkpi.push(req[i]);
								}
						    }
						 var warnobj={"warnpeoplename":$("#warinpeoplename").val(),"warntype":"1","warncontant":$('input:radio[name="warincontant"]:checked').val(),"warnphone":$("#warinphone").val(),"warnemail":$("#warinemail").val()};
						 var dangerobj={"dangerpeoplename":$("#dangerpeople").val(),"dangertype":"2","dangercontant":$('input:radio[name="dangercontant"]:checked').val(),"dangerphone":$("#dangerphone").val(),"dangeremail":$("#dangeremail").val()};
						 var seriousobj={"seriouspeoplename":$("#seriouspeople").val(),"serioustype":"3","seriouscontant":$('input:radio[name="seriouscontant"]:checked').val(),"seriousphone":$("#seriousphone").val(),"seriousemail":$("#seriousemail").val()};
						 var contantpople=[warnobj,dangerobj,seriousobj];
						  var dataEnd={
								//规则配置数据
								"updateUser":userObj.name,
								"tablerule":JSON.stringify(conditons),
								"rulekpi":JSON.stringify(rulekpi),
								//联系人
								"contantpeople":JSON.stringify(contantpople),
								//频率
								"freqkpi":JSON.stringify(freqkpi),
								"frecollection":$scope.selectedSite2,
								"frewarin":$scope.selectedSite3,
								//运维命令
//								"modifykpi":JSON.stringify(modifykpi),
								"modifies":JSON.stringify(modifies)
							};		
						$.ajax({
								type : "POST",
								url : basePath +"/saveInfo",
								dataType : "json",
								contentType : 'application/json;charset=utf-8',//指定为json类型 
								data :JSON.stringify(dataEnd),
								success : function(data) {
									 console.log(data);
									 gotoStep(7);
									alert("插入成功");
								}
							});
					})
								
						
					})
			
			
})();
